package com.hy.utils;


import com.hy.entitys.Chapter;


import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.SSLContext;
import java.awt.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.apache.catalina.manager.host.Constants.CHARSET;


public class StoryUtils {
    //日志
    private static final Logger log = LoggerFactory.getLogger(StoryUtils.class);


    //使用 HttpClient获取目标httpResponse
    public Elements crawl(String url,String select,Map<String, Object> params){

        if (params != null && !params.isEmpty()){
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
            }
            try {
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs,"utf8"));

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        HttpGet httpGet =new HttpGet(url);
        HttpClientBuilder builder = null;
        try {
            //添加SSL认证
            SSLContextBuilder context_b = SSLContextBuilder.create();
            context_b.loadTrustMaterial(new TrustSelfSignedStrategy());
            SSLContext ssl_context = context_b.build();
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ssl_context,new DefaultHostnameVerifier());
            builder = HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        try(
                //CloseableHttpClient httpClient = HttpClientBuilder.create().build();
                CloseableHttpClient httpClient = builder.build();
                CloseableHttpResponse httpResponse =httpClient.execute(httpGet);
        ){

            //把响应对象转成String
            // 解决中文乱码
            String result = EntityUtils.toString(httpResponse.getEntity(),"utf8");
            //通过响应对象字符串获取dom
            Document dom = Jsoup.parse(result);

            //配置跟路径解决绝多网站对路径相对路径不一致
            dom.setBaseUri(url);
            //通过选择器拿到要抓取的对象
            Elements elements=dom.select(select);
            return elements;
        }catch (Exception e){
            e.printStackTrace();
            log.info("获取url返回失败url:"+url);
        }
        return null;
    }



    //获取章节集合
    public List<Chapter> getChapter(String url,String select){
        List<Chapter> chapters= new ArrayList<>();
        Elements elements = crawl(url, select,null);
        //遍历赋值加到返回集合
        elements.forEach(element->{
            chapters.add(new Chapter(element.text(),element.absUrl("href")));
        });
        return chapters;
    }

}
